package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.dto.DishDto;
import com.reggie.pojo.Dish;
import com.reggie.pojo.SetmealDish;
import com.reggie.service.DishService;
import com.reggie.utils.Result;
import com.reggie.dto.SetmealDto;
import com.reggie.pojo.Category;
import com.reggie.pojo.Setmeal;
import com.reggie.service.CategoryService;
import com.reggie.service.SetmealDishService;
import com.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody SetmealDto setmealDto) {
        log.warn(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return Result.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<SetmealDto>> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        //排序
        wrapper.orderByDesc(Setmeal::getCreateTime);
        //查询
        setmealService.page(pageInfo, wrapper);

        //将公共字段拷贝到dtoPage中
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        //添加套餐分类名称
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //公共字段拷贝
            BeanUtils.copyProperties(item, setmealDto);
            Category category = null;
            if (item.getCategoryId() != null) {
                //获取菜品分类名称
                category = categoryService.getById(item.getCategoryId());
            }
            //特殊字段赋值
            assert category != null;
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return Result.success(dtoPage);
    }

    /**
     * 删除套餐即套餐与菜品关联关系
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam List<Long> ids) {
        setmealService.deleteWithDish(ids);
        return Result.success("删除套餐成功");
    }

    /**
     * 修改套餐状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> status(@PathVariable int status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            //找到对应数据
            Setmeal byId = setmealService.getById(id);
            //设置状态
            byId.setStatus(status);
            //更新数据
            setmealService.updateById(byId);
        }

        if (status == 0) {
            return Result.success("停售成功");
        }
        return Result.success("起售成功");
    }

    /**
     * 根据ID查询套餐信息
     *
     * @param id 套餐id
     * @return 返回套餐信息即相关菜品信息
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto byIdWithDish = setmealService.getByIdWithDish(id);
        return Result.success(byIdWithDish);
    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDish(setmealDto);
        return Result.success("修改成功");
    }

    /**
     * 检查套餐名是否重复
     *
     * @param name
     * @return
     */
    @GetMapping("/check/{name}")
    public Result<String> check(@PathVariable String name) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(name != null, Setmeal::getName, name);

        Setmeal setmeal = setmealService.getOne(wrapper);
        if (setmeal != null) {
            return Result.error("套餐名称重复");
        }
        return Result.success("套餐名未重复");
    }

    /**
     * 根据分类查询套餐
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<Setmeal>> list(Setmeal setmeal) {
        //条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(Setmeal::getStatus, 1);
        //排序规则
        wrapper.orderByDesc(Setmeal::getCreateTime);

        List<Setmeal> setmealList = setmealService.list(wrapper);
        return Result.success(setmealList);
    }

    /**
     * 手机端获取套餐详情
     * @param id 套餐Id
     * @return List<dishDto> 对象
     */
    @GetMapping("/dish/{id}")
    public Result<List<DishDto>> getSetmealDish(@PathVariable Long id) {
        log.info(id.toString());
        List<SetmealDish> setmealDishes = setmealService.getByIdWithDish(id).getSetmealDishes();

        //数据处理，添加图片信息
        List<DishDto> dishDtos = setmealDishes.stream().map((item) -> {
            //添加图片信息
            Long dishId = item.getDishId();
            Dish dish = dishService.getById(dishId);
            //创建Dto对象
            DishDto dishDto = new DishDto();
            //拷贝公共字段
            BeanUtils.copyProperties(dish,dishDto);
            //添加份数
            dishDto.setCopies(item.getCopies());
            return dishDto;
        }).collect(Collectors.toList());


        if (dishDtos != null) {
            return Result.success(dishDtos);
        }
        return Result.error("没有关联菜品");
    }
}
